package com.eastfair.venuebooking.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.eastfair.common.api.ContractFeign;
import com.eastfair.core.base.R;
import com.eastfair.core.exception.BizException;
import com.eastfair.pay.dto.ContractDTO;
import com.eastfair.pay.dto.PaymentPlanDTO;
import com.eastfair.pay.enums.PayStateEnum;
import com.eastfair.pay.vo.ContractFinanceVO;
import com.eastfair.venuebooking.dto.ContractManageDTO;
import com.eastfair.venuebooking.service.VenueBookingContractService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 支付系统合同服务.
 *
 * @author dqq
 * @date 2022 /6/25
 */
@Service
@Slf4j
public class VenueBookingContractServiceImpl implements VenueBookingContractService {

    @Resource
    private ContractFeign contractFeign;

    @Override
    public boolean saveOrUpdate(ContractManageDTO contractManageDTO) {
        // 查询支付系统的合同
        CopyOptions copyOptions = CopyOptions.create()
                .ignoreNullValue()
                .setIgnoreProperties("id");
        ContractDTO contractDTO = BeanUtil.toBean(contractManageDTO, ContractDTO.class, copyOptions);
        contractDTO.setContractId(contractManageDTO.getId());
        contractDTO.setContractPayState(PayStateEnum.UN_PAY.getCode());
        // 支付计划添加合同id和合同名称
        List<PaymentPlanDTO> paymentPlanDTOList = contractDTO.getPaymentPlanDTOList();
        if (paymentPlanDTOList != null && !paymentPlanDTOList.isEmpty()) {
            paymentPlanDTOList
                    .forEach(payApiPaymentPlanDTO -> {
                        payApiPaymentPlanDTO.setBusinessId(contractDTO.getId());
                        payApiPaymentPlanDTO.setBusinessName(contractDTO.getContractName());
                    });
        }
        R<?> result = contractFeign.saveOrUpdate(contractDTO);
        if (!result.getIsSuccess()) {
            throw BizException.wrap(result.getCode(), result.getMsg());
        }
        return true;
    }

    @Override
    public boolean isCollected(Long contactId) {
        R<?> result = contractFeign.isCollected(contactId);
        if (!result.getIsSuccess()) {
            throw BizException.wrap(result.getCode(), result.getMsg());
        }
        return true;
    }

    @Override
    public boolean delete(Long contractId) {
        R<?> result = contractFeign.delete(contractId);
        Boolean data = (Boolean) result.getData();
        if (!result.getIsSuccess() || !data) {
            throw BizException.wrap(result.getCode(), result.getMsg());
        }
        return true;
    }

    @Override
    public ContractFinanceVO queryFinance(Long contractId) {
        R<ContractFinanceVO> result = contractFeign.queryFinance(contractId);
        if (!result.getIsSuccess()) {
            throw BizException.wrap(result.getCode(), result.getMsg());
        }
        return result.getData();
    }
}
